﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace EWms.WebApi.Filter
{
    public class ApiExceptionAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception is ApiException)
            {
                ApiException exception = (ApiException)actionExecutedContext.Exception;
                Result result = new Result(exception.Code, exception.Msg, null);
                actionExecutedContext.Result = new ContentResult()
                {
                    Content = JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings
                    {
                        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                    }),
                    ContentType = "application/json"
                };
            }
            else
            {
                Exception exception = actionExecutedContext.Exception;
                Result result = new Result(500, exception.Message, null);
                actionExecutedContext.Result = new ContentResult()
                {
                    Content = JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings
                    {
                        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                    }),
                    ContentType = "application/json"
                };
            }
        }
    }
}
